#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天翼云盘PC版文件管理类
包含复制、删除、重命名、移动等文件管理操作
"""

import time
import json
from typing import Dict, List, Optional, Any
from urllib.parse import quote

from .base_client import API_URL

class FileManagement:
    """文件管理类"""
    
    def copy_file(self, file_id: str, target_folder_id: str, is_family: bool = False) -> bool:
        """复制文件"""
        if not self.is_login():
            print("未登录，无法复制文件")
            return False
        
        if is_family:
            url = f"{API_URL}/family/file/batchCopyFiles.action"
        else:
            url = f"{API_URL}/batchCopyFiles.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'fileIds': file_id,
            'targetFolderId': target_folder_id
        })
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"复制文件 URL: {url}")
            self.logger.debug(f"复制文件 数据: {data}")
            self.logger.debug(f"复制文件 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"复制文件响应状态码: {response.status_code}")
                self.logger.debug(f"复制文件响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"文件复制成功")
                    return True
                else:
                    print(f"复制文件失败: {result.get('res_message')}")
        except Exception as e:
            print(f"复制文件失败: {e}")
        return False
    
    def delete_file(self, file_id: str, is_family: bool = False) -> bool:
        """删除文件"""
        if not self.is_login():
            print("未登录，无法删除文件")
            return False
        
        if is_family:
            url = f"{API_URL}/family/file/batchDeleteFiles.action"
        else:
            url = f"{API_URL}/batchDeleteFiles.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'fileIds': file_id
        })
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"删除文件 URL: {url}")
            self.logger.debug(f"删除文件 数据: {data}")
            self.logger.debug(f"删除文件 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"删除文件响应状态码: {response.status_code}")
                self.logger.debug(f"删除文件响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"文件删除成功")
                    return True
                else:
                    print(f"删除文件失败: {result.get('res_message')}")
        except Exception as e:
            print(f"删除文件失败: {e}")
        return False
    
    def rename_file(self, file_id: str, new_name: str, is_family: bool = False) -> bool:
        """重命名文件"""
        if not self.is_login():
            print("未登录，无法重命名文件")
            return False
        
        if is_family:
            url = f"{API_URL}/family/file/renameFile.action"
        else:
            url = f"{API_URL}/renameFile.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'fileId': file_id,
            'fileName': new_name
        })
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"重命名文件 URL: {url}")
            self.logger.debug(f"重命名文件 数据: {data}")
            self.logger.debug(f"重命名文件 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"重命名文件响应状态码: {response.status_code}")
                self.logger.debug(f"重命名文件响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"文件重命名成功: {new_name}")
                    return True
                else:
                    print(f"重命名文件失败: {result.get('res_message')}")
        except Exception as e:
            print(f"重命名文件失败: {e}")
        return False
    
    def move_file(self, file_id: str, target_folder_id: str, is_family: bool = False) -> bool:
        """移动文件"""
        if not self.is_login():
            print("未登录，无法移动文件")
            return False
        
        if is_family:
            url = f"{API_URL}/family/file/batchMoveFiles.action"
        else:
            url = f"{API_URL}/batchMoveFiles.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'fileIds': file_id,
            'targetFolderId': target_folder_id
        })
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"移动文件 URL: {url}")
            self.logger.debug(f"移动文件 数据: {data}")
            self.logger.debug(f"移动文件 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"移动文件响应状态码: {response.status_code}")
                self.logger.debug(f"移动文件响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"文件移动成功")
                    return True
                else:
                    print(f"移动文件失败: {result.get('res_message')}")
        except Exception as e:
            print(f"移动文件失败: {e}")
        return False
    
    def create_batch_task(self, task_type: str, file_ids: List[str], target_folder_id: str = None, 
                         is_family: bool = False) -> Optional[str]:
        """创建批量任务
        
        Args:
            task_type: 任务类型 (COPY, MOVE, DELETE)
            file_ids: 文件ID列表
            target_folder_id: 目标文件夹ID（复制和移动时需要）
            is_family: 是否为家庭云
            
        Returns:
            任务ID，失败时返回None
        """
        if not self.is_login():
            print("未登录，无法创建批量任务")
            return None
        
        if is_family:
            url = f"{API_URL}/family/file/createBatchTask.action"
        else:
            url = f"{API_URL}/createBatchTask.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'type': task_type,
            'fileIds': ','.join(file_ids)
        })
        
        if target_folder_id:
            data['targetFolderId'] = target_folder_id
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"创建批量任务 URL: {url}")
            self.logger.debug(f"创建批量任务 数据: {data}")
            self.logger.debug(f"创建批量任务 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"创建批量任务响应状态码: {response.status_code}")
                self.logger.debug(f"创建批量任务响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    task_id = result.get('taskId')
                    print(f"批量任务创建成功，任务ID: {task_id}")
                    return task_id
                else:
                    print(f"创建批量任务失败: {result.get('res_message')}")
        except Exception as e:
            print(f"创建批量任务失败: {e}")
        return None
    
    def check_batch_task(self, task_id: str, is_family: bool = False) -> Optional[Dict[str, Any]]:
        """检查批量任务状态
        
        Args:
            task_id: 任务ID
            is_family: 是否为家庭云
            
        Returns:
            任务状态信息，失败时返回None
        """
        if not self.is_login():
            print("未登录，无法检查批量任务")
            return None
        
        if is_family:
            url = f"{API_URL}/family/file/checkBatchTask.action"
        else:
            url = f"{API_URL}/checkBatchTask.action"
        
        headers = self.signature_header(url, "GET", "", is_family)
        params = self.client_suffix()
        params['taskId'] = task_id
        
        if is_family:
            params['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"检查批量任务 URL: {url}")
            self.logger.debug(f"检查批量任务 参数: {params}")
            self.logger.debug(f"检查批量任务 请求头: {headers}")
        
        try:
            response = self.session.get(url, headers=headers, params=params)
            if self.enable_debug:
                self.logger.debug(f"检查批量任务响应状态码: {response.status_code}")
                self.logger.debug(f"检查批量任务响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    return result
                else:
                    print(f"检查批量任务失败: {result.get('res_message')}")
        except Exception as e:
            print(f"检查批量任务失败: {e}")
        return None
    
    def wait_batch_task(self, task_id: str, is_family: bool = False, timeout: int = 300) -> bool:
        """等待批量任务完成
        
        Args:
            task_id: 任务ID
            is_family: 是否为家庭云
            timeout: 超时时间（秒）
            
        Returns:
            任务是否成功完成
        """
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            task_info = self.check_batch_task(task_id, is_family)
            if not task_info:
                print("检查任务状态失败")
                return False
            
            status = task_info.get('taskStatus')
            if status == 4:  # 任务完成
                print("批量任务完成")
                return True
            elif status == 7:  # 任务失败
                print("批量任务失败")
                return False
            elif status in [0, 1, 2]:  # 任务进行中
                print(f"任务进行中，状态: {status}")
                time.sleep(2)
            else:
                print(f"未知任务状态: {status}")
                time.sleep(2)
        
        print("等待任务完成超时")
        return False
    
    def get_conflict_task_info(self, task_id: str, is_family: bool = False) -> Optional[Dict[str, Any]]:
        """获取冲突任务信息
        
        Args:
            task_id: 任务ID
            is_family: 是否为家庭云
            
        Returns:
            冲突任务信息，失败时返回None
        """
        if not self.is_login():
            print("未登录，无法获取冲突任务信息")
            return None
        
        if is_family:
            url = f"{API_URL}/family/file/getConflictTaskInfo.action"
        else:
            url = f"{API_URL}/getConflictTaskInfo.action"
        
        headers = self.signature_header(url, "GET", "", is_family)
        params = self.client_suffix()
        params['taskId'] = task_id
        
        if is_family:
            params['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"获取冲突任务信息 URL: {url}")
            self.logger.debug(f"获取冲突任务信息 参数: {params}")
            self.logger.debug(f"获取冲突任务信息 请求头: {headers}")
        
        try:
            response = self.session.get(url, headers=headers, params=params)
            if self.enable_debug:
                self.logger.debug(f"获取冲突任务信息响应状态码: {response.status_code}")
                self.logger.debug(f"获取冲突任务信息响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    return result
                else:
                    print(f"获取冲突任务信息失败: {result.get('res_message')}")
        except Exception as e:
            print(f"获取冲突任务信息失败: {e}")
        return None
    
    def manage_batch_task(self, task_id: str, action: str, conflict_files: List[Dict[str, Any]] = None, 
                         is_family: bool = False) -> bool:
        """管理批量任务
        
        Args:
            task_id: 任务ID
            action: 操作类型 (CONTINUE, CANCEL, RETRY)
            conflict_files: 冲突文件处理信息
            is_family: 是否为家庭云
            
        Returns:
            操作是否成功
        """
        if not self.is_login():
            print("未登录，无法管理批量任务")
            return False
        
        if is_family:
            url = f"{API_URL}/family/file/manageBatchTask.action"
        else:
            url = f"{API_URL}/manageBatchTask.action"
        
        headers = self.signature_header(url, "POST", "", is_family)
        data = self.client_suffix()
        data.update({
            'taskId': task_id,
            'action': action
        })
        
        if conflict_files:
            data['conflictFiles'] = json.dumps(conflict_files)
        
        if is_family:
            data['familyId'] = self.family_id
        
        if self.enable_debug:
            self.logger.debug(f"管理批量任务 URL: {url}")
            self.logger.debug(f"管理批量任务 数据: {data}")
            self.logger.debug(f"管理批量任务 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"管理批量任务响应状态码: {response.status_code}")
                self.logger.debug(f"管理批量任务响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"批量任务管理成功")
                    return True
                else:
                    print(f"管理批量任务失败: {result.get('res_message')}")
        except Exception as e:
            print(f"管理批量任务失败: {e}")
        return False
    
    def save_family_file_to_person_cloud(self, file_id: str, target_folder_id: str = "-11") -> bool:
        """保存家庭云文件到个人云
        
        Args:
            file_id: 家庭云文件ID
            target_folder_id: 个人云目标文件夹ID
            
        Returns:
            操作是否成功
        """
        if not self.is_login():
            print("未登录，无法保存文件到个人云")
            return False
        
        url = f"{API_URL}/family/file/saveFamilyFileToPersonCloud.action"
        
        headers = self.signature_header(url, "POST", "", True)
        data = self.client_suffix()
        data.update({
            'fileId': file_id,
            'targetFolderId': target_folder_id,
            'familyId': self.family_id
        })
        
        if self.enable_debug:
            self.logger.debug(f"保存家庭云文件到个人云 URL: {url}")
            self.logger.debug(f"保存家庭云文件到个人云 数据: {data}")
            self.logger.debug(f"保存家庭云文件到个人云 请求头: {headers}")
        
        try:
            response = self.session.post(url, headers=headers, data=data)
            if self.enable_debug:
                self.logger.debug(f"保存家庭云文件到个人云响应状态码: {response.status_code}")
                self.logger.debug(f"保存家庭云文件到个人云响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('res_code') == 0:
                    print(f"文件保存到个人云成功")
                    return True
                else:
                    print(f"保存文件到个人云失败: {result.get('res_message')}")
        except Exception as e:
            print(f"保存文件到个人云失败: {e}")
        return False